// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, TextInput, ScrollView, InteractionManager } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import Icon from 'react-native-vector-icons/dist/Ionicons';
import { Actions } from 'react-native-router-flux';
import * as ActionTypes from '../../constants/constants.js'

// antd 按需加载
import { Tabs, Toast, Stepper } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { list } from './module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用import console = require('console');
import { Status, NavBar, RefreshScrollView, Book } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { press, size, ScreenWidth } from '../../util/utils.js'
class Purchasing extends Component {
  constructor(props) {
    super(props)
    this.state = {
      refreshing: false,
      keyword: null,
      bookList: [],
      visible: false
    }
    this.list = list.bind(this)
  }

  componentDidMount() {
    const { purchasingGood } = this.props
    const { keyword } = this.state
    let bookType = 1
    this.list(`bookType=${bookType}&keyword=${this.search._lastNativeText}`)
  }

  componentWillUnmount() {
    const { dispatch } = this.props
    dispatch({
      type: ActionTypes.purchasingGoodReset,
    })
  }

  onRefresh = () => {
    this.setState({ refreshing: true });
    this.list(`bookType=${1}&keyword=${this.search._lastNativeText}`).then(res => {
      this.setState({ refreshing: false });
    })
  }


  handleSearch() {
    this.list(`bookType=1&keyword=${this.search._lastNativeText}`)
  }

  renderBuy() {
    const { visible, bookList } = this.state
    if (visible) {
      return (
        <View style={{
          height: 240,
          padding: 0,
          margin: 0,
          borderTopWidth: .5,
          borderStyle: 'solid',
          borderColor: '#ddd',
          flexDirection: 'column',
        }}>
          <View style={{
            padding: 15,
            paddingBottom: 0
          }}>
            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>书籍代购</Text>
            <Text style={{ fontSize: 12, color: '#61676F', lineHeight: 16, }}>没有搜索到想要的书籍，请在下面输入书籍名称和ISBN</Text>
          </View>
          <ScrollView
            style={{
              padding: 15,
              flex: 1,
            }}>
            {bookList.map((item, index) => {
              return (
                <View
                  key={index}
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}>
                  <TextInput
                    placeholder="书籍名称"
                    placeholderTextColor="#c8c8ca"
                    value={item.bookName}
                    onChangeText={(text) => { this.handleBookName(text, index) }}
                    style={{
                      flex: 1,
                      padding: 0,
                      paddingLeft: 5,
                      paddingRight: 5,
                      fontSize: 14,
                      lineHeight: 28,
                      height: 28,
                      color: '#333',
                      borderWidth: .5,
                      borderStyle: 'solid',
                      borderColor: '#ddd',
                      marginRight: 10,
                    }}
                    underlineColorAndroid="transparent"
                  />
                  <TextInput
                    placeholder="ISBN"
                    placeholderTextColor="#c8c8ca"
                    style={{
                      flex: 1,
                      padding: 0,
                      paddingLeft: 5,
                      paddingRight: 5,
                      fontSize: 14,
                      lineHeight: 28,
                      height: 28,
                      color: '#333',
                      borderWidth: .5,
                      borderStyle: 'solid',
                      borderColor: '#ddd',
                      marginRight: 10,
                    }}
                    value={item.isbn}
                    onChangeText={(text) => { this.handleIsBn(text, index) }}
                    underlineColorAndroid="transparent"
                  />
                  <Stepper
                    styles={{
                      flexDirection: 'row',
                      alignItems: 'center',
                    }}
                    inputStyle={{
                      padding: 8
                    }}
                    defaultValue={item.quantity}
                    value={item.quantity}
                    onChange={(text) => { this.handleQuantity(text, index) }}
                  />
                  {index > 0 ? (
                    <TouchableOpacity onPress={() => this.closeBuy(index)} style={{
                      paddingLeft: 10
                    }}>
                      <Icon name="md-close" size={30} color={'#333'} />
                    </TouchableOpacity>
                  ) : (
                      <TouchableOpacity onPress={this.addBuy} style={{
                        paddingLeft: 10
                      }}>
                        <Icon name="md-add" size={30} color={'#333'} />
                      </TouchableOpacity>
                    )}
                </View>
              )
            })}
          </ScrollView>

          <View style={{
            height: 44,
          }}>
            <TouchableOpacity
              style={{
              }}
              onPress={() => {
                this.handleSubmitBook()
              }}
              style={{
                borderWidth: .5,
                borderStyle: 'solid',
                borderColor: '#ddd',
                backgroundColor: '#f23030',
                color: '#fff'
              }}
            >
              <Text style={{ fontSize: 14, textAlign: 'center', color: '#fff', lineHeight: 44, }}>加入代购</Text>
            </TouchableOpacity>
          </View>
        </View>
      )
    }
  }

  handleBookName = (text, index) => {
    let bookList = [...this.state.bookList]
    bookList[index].bookName = text
    this.setState({
      bookList
    })
  }

  handleIsBn = (text, index) => {
    let bookList = [...this.state.bookList]
    bookList[index].isbn = text
    this.setState({
      bookList
    })
  }

  handleQuantity = (text, index) => {
    let bookList = [...this.state.bookList]
    if (text <= 0) {
      bookList.splice(index, 1)
    } else {
      bookList[index].quantity = text
    }
    if (bookList.length <= 0) {
      this.setState({
        visible: false
      })
    }
    this.setState({
      bookList
    })
  }

  handleSubmitBook = () => {
    const { dispatch } = this.props
    const { bookList } = this.state
    for (let i = 0; i < bookList.length; i++) {
      let item = bookList[i]
      if (!item.bookName) {
        Toast.fail('请输入书名', 1, null, false)
        return
      }
      if (!item.isbn) {
        Toast.fail('请输入isbn', 1, null, false)
        return
      }
    }
    dispatch({
      type: ActionTypes.confirmBook,
      data: {
        bookList
      }
    })
    Actions.submitBook()
  }

  addBuy = (data) => {
    let bookList = [...this.state.bookList]
    let isBuy = false
    if (data) {
      bookList.map(item => {
        if (item.isbn == data.isbn) {
          item.quantity += 1
          isBuy = true
        }
      })
      if (!isBuy) {
        bookList.push({
          pic: data.image_url,
          bookName: data.title,
          isbn: data.isbn,
          quantity: 1
        })
      }
    } else {
      bookList.push({
        pic: '',
        bookName: '',
        isbn: '',
        quantity: 1
      })
    }
    this.setState({
      visible: true,
      bookList
    })
  }
  closeBuy = (index) => {
    let bookList = [...this.state.bookList]
    bookList.splice(index, 1)
    this.setState({
      bookList
    })
  }

  render() {
    const { refreshing } = this.state
    const { purchasingGood } = this.props
    return (
      <View style={Style.container}>
        <Status />
        <View style={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          backgroundColor: '#fff',
          borderBottomWidth: 1,
          borderStyle: 'solid',
          borderBottomColor: '#e5e5e5'
        }}>
          <TouchableOpacity
            style={{
              width: 44,
              height: 44,
              alignItems: 'center',
              justifyContent: 'center',
            }}
            onPress={() => {
              Actions.pop()
            }}
          >
            <Icon name="md-arrow-back" size={22} color="#232326" />
          </TouchableOpacity>
          <View style={{
            flex: 1,
            height: 30,
          }}>
            <View
              style={{
                paddingVertical: 0,
                paddingHorizontal: 15,
                borderRadius: 15,
                height: 30,
                backgroundColor: '#f7f7f7',
              }}
            >
              <TextInput
                ref={(r) => this.search = r}
                placeholder="请输入书籍名称"
                placeholderTextColor="#c8c8ca"
                style={{
                  fontSize: 16,
                  borderWidth: 0,
                  color: '#333',
                  lineHeight: 30,
                  padding: 0
                }}
                underlineColorAndroid="transparent"
              />
            </View>
          </View>
          <TouchableOpacity
            style={{
              width: 44,
              height: 44,
              alignItems: 'center',
              justifyContent: 'center',
            }}
            onPress={() => {
              this.handleSearch()
            }}
          >
            <Icon name="md-search" size={22} color="#252525" />
          </TouchableOpacity>
        </View>
        <RefreshScrollView
          style={Style.content}
          refreshing={refreshing}
          onRefresh={this.onRefresh}
        >
          {purchasingGood.map((item, index) => {
            return <Book addBuy={this.addBuy} data={item} />
          })}
        </RefreshScrollView>
        {this.renderBuy()}
      </View >
    );
  }
}


export default connect(({ purchasingGood }) => ({
  purchasingGood
}))(pureRender(Purchasing))
